package com.chinamobile.maps.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.chinamobile.maps.dao.IGridDAO;
import com.chinamobile.maps.dao.IRegionsDAO;
import com.chinamobile.maps.orm.Grid;
import com.chinamobile.maps.orm.Regions;
import com.chinamobile.maps.util.JsonUtil;
import com.chinamobile.maps.util.LoggerUtil;
import com.chinamobile.maps.util.Struts2Util;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @ClassName:   GridAction
 * @Description: TODO
 * @author:      frankwong
 * @date:        2012-10-28 下午9:52:37
 *
 */
public class GridAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 3297845442352903887L;
	
	public IGridDAO gridDao = null;
	public IRegionsDAO regionDao = null;
	
	public void addGrid(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			request.setCharacterEncoding("UTF-8");
			String name = URLDecoder.decode(String.valueOf(request.getParameter("name")),"UTF-8");
			Integer regionId = Integer.parseInt(request.getParameter("regionId"));
			String regionName = URLDecoder.decode(String.valueOf(request.getParameter("regionName")),"UTF-8");
			String microRegionIds = String.valueOf(request.getParameter("microRegionIds"));
			String[] microRegionIdArray = microRegionIds.split(",");
			int idCount = microRegionIdArray.length;
			Grid grid = new Grid();
			grid.setName(name);
			this.gridDao.addGrid(grid);
			grid = this.gridDao.getGridByname(name);
			int gridId = grid.getId();
			
			int mainHallCount =0;
			int cooperativeHallCount = 0;
			int unicomHallCount =0;
			int telecomHallCount =0;
			int specialAgentCount =0;
			int authorizedPointCount =0;
			int villagePointCount =0;
			int shareChannelCount =0;
			
			Regions region = null;
			for(int i = 0;i<idCount;i++){
				region = this.regionDao.getRegionsById(Integer.parseInt(microRegionIdArray[i]));
				region.setGridId(gridId);
				this.regionDao.updateRegions(region);
				mainHallCount+=region.getMainHallCount();
				cooperativeHallCount+=region.getCooperativeHallCount();
				unicomHallCount +=region.getUnicomHallCount();
				telecomHallCount +=region.getTelecomHallCount();
				specialAgentCount+=region.getSpecialAgentCount();
				authorizedPointCount+=region.getAuthorizedPointCount();
				villagePointCount+=region.getVillagePointCount();
				shareChannelCount+=region.getShareChannelCount();
			}
			grid.setMainHallCount(mainHallCount);
			grid.setCooperativeHallCount(cooperativeHallCount);
			grid.setUnicomHallCount(unicomHallCount);
			grid.setTelecomHallCount(telecomHallCount);
			grid.setSpecialAgentCount(specialAgentCount);
			grid.setAuthorizedPointCount(authorizedPointCount);
			grid.setVillagePointCount(villagePointCount);
			grid.setShareChannelCount(shareChannelCount);
			grid.setParentRegionId(regionId);
			grid.setParentRegionName(regionName);
			this.gridDao.updateGrid(grid);
			LoggerUtil.LogInfo("增加网格:"+grid.getName());
			out.print("{\"result\":true}");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}

	public void editGrid(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			int id = Integer.parseInt(request.getParameter("id"));
			Grid grid = this.gridDao.getGridById(id);
			String oldIds = request.getParameter("oldIds");
			String newIds = String.valueOf(request.getParameter("newIds"));
			
			String[] oldIdsStrArray = oldIds.split(",");
			String[] newIdsStrArray = newIds.split(",");
			int length1 = oldIdsStrArray.length;
			int length2 = newIdsStrArray.length;
			
			List<String> oldIdsArray =  new ArrayList<String>();
			List<String> newIdsArray =  new ArrayList<String>();
			for(int i = 0;i<length1;i++){
				oldIdsArray.add(oldIdsStrArray[i]);
			}
			for(int i = 0;i<length2;i++){
				newIdsArray.add(newIdsStrArray[i]);
			}
			for(int i = 0;i<oldIdsArray.size();i++){
				for(int j=0;j<newIdsArray.size();j++){
					if(oldIdsArray.get(i).equals(newIdsArray.get(j))){
						oldIdsArray.remove(i--);
						newIdsArray.remove(j--);
						break;
					}
				}
			}
			int oldCount = oldIdsArray.size();
			int newCount = newIdsArray.size();
			Regions region;
			for(int i = 0;i<oldCount;i++){
				region = this.regionDao.getRegionsById(Integer.parseInt(oldIdsArray.get(i)));
				if(region != null){
					region.setGridId(null);
					this.regionDao.updateRegions(region);
				}
			}
			for(int i = 0;i<newCount;i++){
				region = this.regionDao.getRegionsById(Integer.parseInt(newIdsArray.get(i)));
				if(region != null){
					region.setGridId(id);
					this.regionDao.updateRegions(region);
				}
			}
			LoggerUtil.LogInfo("编辑网格:"+grid.getName());
			out.print("{\"result\":true}");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void getGridInfo() {
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer gridId = Integer.parseInt(request.getParameter("id"));
			Integer regionId = Integer.parseInt(request.getParameter("regionId"));
			List<Regions> regionsHave = this.regionDao
					.getObjects("from Regions r where r.parentRegionId ="
							+ regionId + " and r.gridId=" + gridId);
			List<Regions> regionsNoHave = this.regionDao
					.getObjects("from Regions r where r.parentRegionId ="
							+ regionId + " and (r.gridId is null or r.gridId !=" + gridId+")");
			int haveCount = regionsHave.size();
			int notHaveCount = regionsNoHave.size();
			StringBuffer sb1 = new StringBuffer();
			StringBuffer sb2 = new StringBuffer();
			int i=0;
			for( ;i<haveCount-1;i++){
				sb1.append(regionsHave.get(i).getId()+","+regionsHave.get(i).getName()+";");
			}
			sb1.append(regionsHave.get(i).getId()+","+regionsHave.get(i).getName());
			i=0;
			for (; i < notHaveCount-1; i++) {
				sb2.append(regionsNoHave.get(i).getId()+","+regionsNoHave.get(i).getName()+";");
			}
			sb2.append(regionsNoHave.get(i).getId()+","+regionsNoHave.get(i).getName());
			List<String> resultJson = new ArrayList<String>();
			resultJson.add(sb1.toString());
			resultJson.add(sb2.toString());
			JSONArray jsonArrayResult = JSONArray.fromObject(resultJson);
			out.print(jsonArrayResult.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	public void getGridsList(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			int pageNumber = Integer.parseInt((request.getParameter("pageNumber")));
			int pageSize = Integer.parseInt((request.getParameter("pageSize")));
			List<Grid> gridsList = this.gridDao.getGrid();
			int count;
			if(gridsList == null){
				out.print("[]");
				return;
			}else{
				count = gridsList.size();
				List<Grid> gridsResult = new ArrayList<Grid>();
				for (int i = pageSize * (pageNumber - 1); i < count
						&& i < pageSize * pageNumber; i++) {
					gridsResult.add(gridsList.get(i));
				}
				Map<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("total", count);
				jsonMap.put("rows", gridsResult);
				JSONObject jsonObject = JSONObject.fromObject(jsonMap,JsonUtil.jsonConfig);
				out.print(jsonObject.toString());
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	public void deleteGrid() {
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer gridId = Integer.parseInt(request.getParameter("id"));
			Grid grid = this.gridDao.getGridById(gridId);
			List<Regions> regionsList = this.regionDao.getObjects("from Regions as regions where regions.gridId="+gridId);
			int regionsCount = regionsList.size();
			for(int i = 0;i<regionsCount;i++){
				regionsList.get(i).setGridId(null);
				this.regionDao.updateRegions(regionsList.get(i));
			}
			this.gridDao.delGrid(gridId);
			LoggerUtil.LogWarn("删除网格:"+grid.getName());
			out.print("{\"result\":false}");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	public void getGridTreeJson(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer regionId = Integer.parseInt(request.getParameter("id"));
			List<Grid> grids = this.gridDao.getObjects("from Grid g where g.parentRegionId = "+regionId);
			if(grids == null){
				out.print("[]");
				out.flush();
				out.close();
				return;
			}
			StringBuilder sb = new StringBuilder();
			int hallCount ;
            int mobileHallCount ;
            int chanelCount ;
            double hallPercent ;
            DecimalFormat df = new DecimalFormat("0.00%");
            String hallPercentStr ;
            String chnelPercent = "100%";
            String jsonTop;
            String jsonStr;
			int count  = grids.size();
			sb.append("[");
			for(int i = 0;i<count;i++){
				hallCount = grids.get(i).getMainHallCount()+grids.get(i).getCooperativeHallCount()+grids.get(i).getUnicomHallCount()+grids.get(i).getTelecomHallCount();
	            mobileHallCount = grids.get(i).getMainHallCount()+grids.get(i).getCooperativeHallCount();
	            chanelCount = grids.get(i).getSpecialAgentCount()+grids.get(i).getVillagePointCount()+grids.get(i).getAuthorizedPointCount()+grids.get(i).getShareChannelCount();
	            if(hallCount != 0){
	            	hallPercent = mobileHallCount*1.00/hallCount;
		            hallPercentStr = df.format(hallPercent);
	            }
	            else{
	            	hallPercentStr = "0%";
	            }
	            String gridName = grids.get(i).getName();
	            jsonTop = "{\"id\":"+grids.get(i).getId()+",\"text\":\""+gridName+"\",\"state\" : \"closed\",\"children\":[";
	            jsonStr = "{\"text\" : \"营业厅("+hallCount+")\",\"state\" : \"open\",\"children\" : [{\"text\" : \"移动营业厅("+mobileHallCount+",市场份额:"+hallPercentStr+")\",\"children\" : [{\"text\" : \"移动主厅("+grids.get(i).getMainHallCount()+")\",\"attributes\":\""+gridName+"Z移动主厅"+"\"}, {\"text\" : \"移动合作厅("+grids.get(i).getCooperativeHallCount()+")\",\"attributes\":\""+gridName+"Z移动合作厅"+"\"}]}, {\"text\" : \"联通营业厅("+grids.get(i).getUnicomHallCount()+")\",\"attributes\":\""+gridName+"Z联通营业厅"+"\"}, {\"text\" : \"电信营业厅("+grids.get(i).getTelecomHallCount()+")\",\"attributes\":\""+gridName+"Z电信营业厅"+"\"}]}, {\"text\" : \"渠道("+chanelCount+",排他渠道份额: "+chnelPercent+")\",\"state\" :\"open\",\"children\" : [{\"text\" : \"特约代理店("+grids.get(i).getSpecialAgentCount()+")\",\"attributes\":\""+gridName+"Z特约代理店"+"\"}, {\"text\" : \"授权销售点("+grids.get(i).getAuthorizedPointCount()+")\",\"attributes\":\""+gridName+"Z授权销售点"+"\"}, {\"text\" : \"村级便民点("+grids.get(i).getVillagePointCount()+")\",\"attributes\":\""+gridName+"Z村级便民点"+"\"}, {\"text\" : \"共享渠道("+grids.get(i).getShareChannelCount()+")\",\"attributes\":\""+gridName+"Z共享渠道"+"\"}]}]},";
	            sb.append(jsonTop);
	            sb.append(jsonStr);
			}
			sb.delete(sb.length()-1, sb.length());
			sb.append("]");
            out.print(sb.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	/**
	 * @return the gridDao
	 */
	public IGridDAO getGridDao() {
		return gridDao;
	}

	/**
	 * @param gridDao the gridDao to set
	 */
	public void setGridDao(IGridDAO gridDao) {
		this.gridDao = gridDao;
	}

	public IRegionsDAO getRegionDao() {
		return regionDao;
	}

	public void setRegionDao(IRegionsDAO regionDao) {
		this.regionDao = regionDao;
	}

}
